#pragma

#include "LockGuard.hpp"
#include <iostream>
#include <queue>
#include <pthread.h>

const int defaultcap = 5;
template<class T>
class BlockQueue
{
public:
    BlockQueue(int cap = defaultcap):_capacity(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
        pthread_cond_init(&_c_cond,nullptr);

    }
    bool Isfull()
    {
        return _q.size() == _capacity;
    }
    void Push(const T& in)//生产者放
    {
        LockGuard lockguard(&_mutex);
        //pthread_mutex_lock(&_mutex);
        while(Isfull())//具有较强健壮性，因为可能存在伪唤醒
        {
            //阻塞
            pthread_cond_wait(&_p_cond,&_mutex);//生产者满了，就要等待消费者，防止频繁申请锁释放锁
        }
        _q.push(in);
        pthread_cond_signal(&_c_cond);//告诉消费者
        //pthread_mutex_unlock(&_mutex);
    }
    bool IsEmpty()
    {
        return _q.size()== 0;
    }
    void Pop(T* out)//消费者取 让指针指向队列的头部
    {

        //pthread_mutex_lock(&_mutex);
        LockGuard lockguard(&_mutex);
        while(IsEmpty())
        {
            //阻塞
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        *out = _q.front();
        _q.pop();
        pthread_cond_signal(&_p_cond);//告诉生产者
        //pthread_mutex_unlock(&_mutex);

    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);

    }
private:
    std::queue<T> _q;
    int _capacity; //_q.size() == _capacity //满了，不能生产，_q.size() == 0 //空了，不能消费
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond;//生产者等待
    pthread_cond_t _c_cond;//消费者等待
};